package cn.lingyangwl.framework.core.utils.spring;

import cn.hutool.extra.spring.SpringUtil;
import cn.lingyangwl.framework.tool.core.exception.Assert;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.Objects;

/**
 * spring工具类 方便在非spring管理环境中获取bean
 *
 * @author shenguangyang
 */
@Component
@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)
public final class SpringUtils extends SpringUtil
        implements BeanFactoryPostProcessor, ApplicationContextAware, DisposableBean {
    private static final Logger log = LoggerFactory.getLogger(SpringUtils.class);

    /**
     * Spring应用上下文环境
     */
    private static ConfigurableListableBeanFactory beanFactory;
    private static ApplicationContext applicationContext = null;
    private static Environment environment = null;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        SpringUtils.beanFactory = beanFactory;
    }

    @PostMapping
    public void init() {
        Assert.notNull(applicationContext, "applicationContext is null");
    }

    /**
     * 取得存储在静态变量中的ApplicationContext.
     */
    public static ApplicationContext getContext() {
        return applicationContext;
    }

    /**
     * 实现ApplicationContextAware接口, 注入Context到静态变量中.
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringUtils.applicationContext = applicationContext;
    }

    /**
     * 获取对象
     *
     * @param name bean名称
     * @return Object 一个以所给名字注册的bean的实例
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        if (Objects.isNull(beanFactory)) {
            return null;
        }
        return (T) beanFactory.getBean(name);
    }

    public static <T> T getBean(String name, Class<T> clz) throws BeansException {
        if (Objects.isNull(beanFactory)) {
            return null;
        }
        return beanFactory.getBean(name, clz);
    }

    /**
     * 获取类型为requiredType的对象
     */
    public static <T> T getBean(Class<T> clz) throws BeansException {
        if (Objects.isNull(beanFactory)) {
            return null;
        }
        return (T) beanFactory.getBean(clz);
    }

    /**
     * 如果BeanFactory包含一个与所给名称匹配的bean定义，则返回true
     */
    public static boolean containsBean(String name) {
        if (Objects.isNull(beanFactory)) {
            return false;
        }
        return beanFactory.containsBean(name);
    }

    /**
     * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 如果与给定名字相应的bean定义没有被找到，
     * 将会抛出一个异常（NoSuchBeanDefinitionException）
     */
    public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
        if (Objects.isNull(beanFactory)) {
            return false;
        }
        return beanFactory.isSingleton(name);
    }

    /**
     * 获取bean的类型
     */
    public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {
        if (Objects.isNull(beanFactory)) {
            return null;
        }
        return beanFactory.getType(name);
    }

    /**
     * 如果给定的bean名字在bean定义中有别名，则返回这些别名
     */
    public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
        return beanFactory.getAliases(name);
    }

    /**
     * 获取aop代理对象
     */
    @SuppressWarnings("unchecked")
    public static <T> T getAopProxy(T invoker) {
        return (T) AopContext.currentProxy();
    }

    /**
     * 清除的ApplicationContext为Null.
     */
    public static void clearContext() {
        if (log.isDebugEnabled()) {
            log.debug("清除 SpringContextHolder 中的ApplicationContext:" + applicationContext);
        }
        applicationContext = null;
    }

    public static String getProperty(String key) {
        if (environment == null) {
            environment = getBean(Environment.class);
        }
        return environment.getProperty(key);
    }

    /**
     * 实现DisposableBean接口, 在Context关闭时清理静态变量.
     */
    @Override
    @SneakyThrows
    public void destroy() {
        SpringUtils.clearContext();
    }
}
